// pages/cmdView/appSet/appSet.js
const util = require("../../../utils/util");
const appControlAPI = requirePlugin("hello-plugin")
const alertUtil = require("../../../utils/alertUtil")
const {

  // API的状态码
  succeed,
  failed,
  timeout,
  unavailable,
  dataError,
  crcError,
  noRecord,

  // 控制类型
  realStepDataUpload,
  realHeartRateDataUpload,
  realBloodOxygenUpload,
  realBloodPressureUpload,
  realHrvUpload,

  // MARK: - 实时数据上传类型

  realTimeDataTypeStep,
  realTimeDataTypeHeartRate,
  realTimeDataTypeBloodOxygen,
  realTimeDataTypeBloodPressure,
  realTimeDataTypeHrv,
  realTimeDataTypeRespirationRate,
  realTimeDataTypeseSportMode,
  realTimeDataTypeCombinedData,


  receivedRealTimeStep,
  receivedRealTimeHeartRate,
  receivedRealTimeBloodOxygen,
  receivedRealTimePressure,
  receivedRealTimeBloodPressure,
  receivedRealTimePPG,
  receivedRealTimeECG,
  receivedRealTimeMonitoringMode,

  // 手环返回 APP 启动单次测量结果
  measureStatus,
  measureECGStatus,
  findPhone,

  // MARK: - 天气类型
  weatherTypeSunny,


  // MARK: - 血糖校准模式
  bloodGlucoseCalibrationModeBeforeMeal,
  bloodGlucoseCalibrationModeAfterMeal,

  // MARK: - 波形上传控制
  waveUploadStateOff,
  waveUploadStateUploadWithOutSerialnumber,
  waveUploadStateUploadSerialnumber,

  waveUploadDataTypePPG,
  waveUploadDataTypeECG,
  waveUploadDataTypeMultiAxisSensor,
  waveUploadDataTypeAmbientLight,

  // 测量控制
  queryHealthDataInvasiveMeasurement,
  stop,
  start,
  continuous,
  // 功能类型
  measureHrData,
  measureBoData,

  // 心电指令key
  electrodeKey,

} = require("../../../utils/constant")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    canvasText: "接收到设备信息："
  },
  onLoad() {
    // this.getRealSport()
  },

  /**
   * 获取实时数据
   */
  queryRealTimeHealthData() {
    alertUtil.handleToast("命令执行中", "loading", 0)
    var that = this
    appControlAPI.receiveRealTimeData(function (realTimeDataType, res) {
      if (realTimeDataType == receivedRealTimeHeartRate) {
        util.printLog(JSON.stringify(res))
        that.setData({
          canvasText: that.data.canvasText + "\n实时心率：" + JSON.stringify(res)
        })
        alertUtil.closeToast()
      } else if (realTimeDataType == receivedRealTimeBloodOxygen) {
        util.printLog(JSON.stringify(res))
        that.setData({
          canvasText: that.data.canvasText + "\n实时血氧：" + JSON.stringify(res)
        })
        alertUtil.closeToast()
      } else if (realTimeDataType == measureStatus) {
        util.printLog(JSON.stringify(res))
        that.setData({
          canvasText: that.data.canvasText + "\n单次测量结果：" + JSON.stringify(res)
        })
        alertUtil.closeToast()
      }
    })
  },


  // mark:-
  // mark : 寻找手环
  findDevice() {
    var that = this
    alertUtil.handleToast("命令执行中", "loading", 0)
    appControlAPI.findDevice(5, 1, (state, res) => {
      if (state == succeed) {
        that.setData({
          canvasText: that.data.canvasText + "\n设置寻找设备：success"
        })
      } else {
        that.setData({
          canvasText: that.data.canvasText + "\n设置寻找设备：fail"
        })
      }
      alertUtil.closeToast()
    })
  },

  findPhone() {
    var that = this
    alertUtil.handleToast("命令执行中", "loading", 0)

     // 监听设备寻找手机
     appControlAPI.receiveRealTimeData((realTimeDataType, res) => {
      if (realTimeDataType == findPhone) { // findPhone == 0x00
        util.printLog(JSON.stringify(res))
        this.setData({
          canvasText: this.data.canvasText + "\n 寻找手机：" + (res == 0 ? "结束" : "开始")
        })
      }
    })

    appControlAPI.setDeviceFindPhone(true, (state, res) => {
      if (state == succeed) {
        that.setData({
          canvasText: that.data.canvasText + "\n 寻找手机：success"
        })
      } else {
        that.setData({
          canvasText: that.data.canvasText + "\n 寻找手机：fail"
        })
      }
      alertUtil.closeToast()
    })


  },


  // mark:-  血压校准
  BloodPressureCalibration() {
    var that = this
    alertUtil.handleToast("命令执行中", "loading", 0)
    appControlAPI.deviceBloodPressureCalibration(115, 75, (state, res) => {
      if (state == succeed) {
        that.setData({
          canvasText: that.data.canvasText + "\n血压校准：success"
        })
      } else {
        that.setData({
          canvasText: that.data.canvasText + "\n血压校准：fail"
        })
      }
      alertUtil.closeToast()
    })
  },

  // MARK: - 血糖校准
  BloodGlucoseCalibration() {

    var that = this
    alertUtil.handleToast("命令执行中", "loading", 0)

    appControlAPI.deviceBloodGlucoseCalibratioin(4, 9, bloodGlucoseCalibrationModeBeforeMeal, (state, res) => {
      if (state == succeed) {
        that.setData({
          canvasText: that.data.canvasText + "\n血糖校准：success"
        })
      } else {
        that.setData({
          canvasText: that.data.canvasText + "\n血糖校准：fail"
        })
      }
      alertUtil.closeToast()
    })
  },

  // MARK: - 尿酸校准
  UricAcidCalibration() {

    var that = this
    alertUtil.handleToast("命令执行中", "loading", 0)

    appControlAPI.deviceUricAcidCalibratioin(700, (state, res) => {
      if (state == succeed) {
        that.setData({
          canvasText: that.data.canvasText + "\n尿酸校准：success"
        })
      } else {
        that.setData({
          canvasText: that.data.canvasText + "\n尿酸校准：fail"
        })
      }
      alertUtil.closeToast()
    })
  },
  // MARK: - 血脂校准
  BloodFatCalibration() {

    var that = this
    alertUtil.handleToast("命令执行中", "loading", 0)

    appControlAPI.deviceBloodFatCalibratioin(2, 99, (state, res) => {
      if (state == succeed) {
        that.setData({
          canvasText: that.data.canvasText + "\n血脂校准：success"
        })
      } else {
        that.setData({
          canvasText: that.data.canvasText + "\n血脂校准：fail"
        })
      }
      alertUtil.closeToast()
    })
  },

  // mark: - 
  // mark: 实时上传健康数据 （血压）
  realTimeBloodPressureUplod(e) {

    var flag = e.currentTarget.dataset.flag === 'true' ? true : false;
    var that = this
    alertUtil.handleToast("命令执行中", "loading", 0)
    util.printLog("发送指令: " + flag, e.currentTarget.dataset)
    appControlAPI.realTimeDataUplod(flag, realTimeDataTypeBloodPressure, (state, res) => {
      // util.printLog("接收成功",res)
      let message = flag ? "开启" : "关闭"
      if (state == 0) {
        that.setData({
          canvasText: that.data.canvasText + "\n" + message + "血压实时上传：success"
        })
      } else {
        that.setData({
          canvasText: that.data.canvasText + "\n" + message + "血压实时上传：fail"
        })
      }
      alertUtil.closeToast()
    })

    appControlAPI.receiveRealTimeData(function (realTimeDataType, res) {
      if (realTimeDataType == receivedRealTimeStep) {
        util.printLog(JSON.stringify(res))
        that.setData({
          canvasText: that.data.canvasText + "\n实时步数：" + JSON.stringify(res)
        })
        alertUtil.closeToast()
      } else if (realTimeDataType == receivedRealTimeHeartRate) {
        util.printLog(JSON.stringify(res))
        that.setData({
          canvasText: that.data.canvasText + "\n实时心率：" + JSON.stringify(res)
        })
        alertUtil.closeToast()
      } else if (realTimeDataType == realBloodPressureUpload) {
        util.printLog(JSON.stringify(res))
        that.setData({
          canvasText: that.data.canvasText + "\n实时数据：" + JSON.stringify(res)
        })
        alertUtil.closeToast()
      } else if (realTimeDataType == measureStatus){
        util.printLog(JSON.stringify(res))
        that.setData({
          canvasText: that.data.canvasText + "\n单次测量结果：" + JSON.stringify(res)
        })
        alertUtil.closeToast()
      } else if (realTimeDataType == receivedRealTimePressure){
        util.printLog(JSON.stringify(res))
        that.setData({
          canvasText: that.data.canvasText + "\n实时压力：" + JSON.stringify(res)
        })
        alertUtil.closeToast()
      } else if (realTimeDataType == receivedRealTimeBloodOxygen){
        util.printLog(JSON.stringify(res))
        that.setData({
          canvasText: that.data.canvasText + "\n实时血氧：" + JSON.stringify(res)
        })
        alertUtil.closeToast()
      }
    })
  },

  /**
   * 开始测量心率
   */
  startMeasureHr() {
    appControlAPI.measureHealthData(queryHealthDataInvasiveMeasurement, start, measureHrData, (state, res) => {
      if (state == succeed) {
        this.setData({
          canvasText: this.data.canvasText + "\n返回数据：" + JSON.stringify(res),
        })
        this.queryRealTimeHealthData();
      } else {
        this.setData({
          canvasText: this.data.canvasText + "\n返回数据：" + JSON.stringify(res),
        })
      }
      alertUtil.closeToast()
    })
  },
  /**
   *手动停止测量心率
   */
  stopMeasureHr() {
    appControlAPI.measureHealthData(queryHealthDataInvasiveMeasurement, stop, measureHrData, (state, res) => {
      if (state == succeed) {
        this.setData({
          canvasText: this.data.canvasText + "\n返回数据：" + JSON.stringify(res),
        })
      } else {
        this.setData({
          canvasText: this.data.canvasText + "\n返回数据：" + JSON.stringify(res),
        })
      }
      alertUtil.closeToast()
    })
  },
    /**
   * 开始测量血氧
   */
  startMeasureBo() {
    appControlAPI.measureHealthData(queryHealthDataInvasiveMeasurement, start, measureBoData, (state, res) => {
      if (state == succeed) {
        this.setData({
          canvasText: this.data.canvasText + "\n返回数据：" + JSON.stringify(res),
        })
        this.queryRealTimeHealthData();
      } else {
        this.setData({
          canvasText: this.data.canvasText + "\n返回数据：" + JSON.stringify(res),
        })
      }
      alertUtil.closeToast()
    })
  },
  /**
   *手动停止测量血氧
   */
  stopMeasureBo() {
    appControlAPI.measureHealthData(queryHealthDataInvasiveMeasurement, stop, measureBoData, (state, res) => {
      if (state == succeed) {
        this.setData({
          canvasText: this.data.canvasText + "\n返回数据：" + JSON.stringify(res),
        })
      } else {
        this.setData({
          canvasText: this.data.canvasText + "\n返回数据：" + JSON.stringify(res),
        })
      }
      alertUtil.closeToast()
    })
  },

  controlSport(){
    
    // 监听运动数据
    appControlAPI.receiveRealTimeData((realTimeDataType, res) => {
      if (realTimeDataType == receivedRealTimeMonitoringMode) {
        util.printLog(JSON.stringify(res))
        this.setData({
          canvasText: this.data.canvasText + "\n 运动数据" + JSON.stringify(res)
        })
      }
    })

    appControlAPI.controlSport(true, 0x01, (state, res) => {
      if (state == succeed) {
        this.setData({
          canvasText: this.data.canvasText + "\n开始运动：" + JSON.stringify(res),
        })
      } else {
        this.setData({
          canvasText: this.data.canvasText + "\n开始运动：" + JSON.stringify(res),
        })
      }
      alertUtil.closeToast()
    })

  },

  systemOperator(e) {
    util.printLog("111", e.currentTarget.dataset)
    var system = e.currentTarget.dataset.system
    var that = this
    alertUtil.handleToast("命令执行中", "loading", 0)
    appControlAPI.deviceSystemOperator(system, (state, res) => {
      if (state == 0) {
        that.setData({
          canvasText: that.data.canvasText + "\n设置系统操作：success"
        })
      } else {
        that.setData({
          canvasText: that.data.canvasText + "\n系统操作：fail"
        })
      }
      alertUtil.closeToast()
    })
  },
  // mark:-
  // mark: 设置天气
  setWeather() {

    var that = this
    alertUtil.handleToast("命令执行中 ", "loading", 0)
    appControlAPI.sendDeviceWeatherData(19, 20, 22, weatherTypeSunny, (state, res) => {

      if (state == 0) {
        that.setData({
          canvasText: that.data.canvasText + "\n设置天气：success"
        })
      } else {
        that.setData({
          canvasText: that.data.canvasText + "\n设置天气：fail"
        })
      }
      alertUtil.closeToast()
    })
  },
  // mark:- 
  // mark: 获取实时步数
  getRealSport() {
    var that = this
    alertUtil.handleToast("命令执行中", "loading", 0)
    appControlAPI.receiveRealTimeData(function (realTimeDataType, res) {

      if (realTimeDataType == receivedRealTimeStep) {
        util.printLog(JSON.stringify(res))
        that.setData({
          canvasText: that.data.canvasText + "\n实时步数：" + JSON.stringify(res)
        })
        alertUtil.closeToast()
      } else if (realTimeDataType == receivedRealTimeHeartRate) {
        util.printLog(JSON.stringify(res))
        that.setData({
          canvasText: that.data.canvasText + "\n实时心率：" + JSON.stringify(res)
        })
        alertUtil.closeToast()
      }
    })
    util.printLog('========dataTyep ' + realStepDataUpload)
    appControlAPI.realTimeDataUplod(true, realStepDataUpload, (state, res) => {
      if (state == succeed) {
        that.setData({
          canvasText: that.data.canvasText + "\n开启实时获取步数：success"
        })
        alertUtil.closeToast()
      }
    })

    appControlAPI.realTimeDataUplod(true, realTimeDataTypeHeartRate, (state, res) => {
      if (state == succeed) {
        that.setData({
          canvasText: that.data.canvasText + "\n开启实时获取心率：success"
        })
        alertUtil.closeToast()
      }
    })
  },

  // MARK: - PPG上传

  // 开始PPG上传
  uploadPPGDataOn() {

    // 开启
    var that = this
    alertUtil.handleToast("命令执行中", "loading", 0)

    appControlAPI.receiveRealTimeData(function (realTimeDataType, res) {

      if (realTimeDataType == receivedRealTimePPG) {
        util.printLog(JSON.stringify(res))
        that.setData({
          canvasText: that.data.canvasText + "\n实时PPG：" + JSON.stringify(res)
        })
        alertUtil.closeToast()
      }
    })

    appControlAPI.waveDataUploadControl(waveUploadStateUploadWithOutSerialnumber, waveUploadDataTypePPG, (state, res) => {

      if (state == 0) {
        that.setData({
          canvasText: that.data.canvasText + "\n开启PPG上传：success"
        })
      } else {
        that.setData({
          canvasText: that.data.canvasText + "\n开启PPG上传：fail"
        })
      }
      alertUtil.closeToast()
    })
  },

  // 结束PPG上传
  uploadPPGDataOff() {

    var that = this
    alertUtil.handleToast("命令执行中", "loading", 0)
    appControlAPI.waveDataUploadControl(waveUploadStateOff, waveUploadDataTypePPG, (state, res) => {

      if (state == 0) {
        that.setData({
          canvasText: that.data.canvasText + "\n关闭PPG上传：success"
        })
      } else {
        that.setData({
          canvasText: that.data.canvasText + "\n关闭PPG上传：fail"
        })
      }
      alertUtil.closeToast()
    })

  },
  // 开启血压测试
  bloodPressureMeasureStart() {
    appControlAPI.receiveRealTimeData((realTimeDataType, res) => {
      if (realTimeDataType == receivedRealTimeBloodPressure) {
        util.printLog(JSON.stringify(res))
        this.setData({
          canvasText: this.data.canvasText + "\n实时血压：" + JSON.stringify(res)
        })
        alertUtil.closeToast()
      } else if (realTimeDataType == electrodeKey) {
        this.setData({
          canvasText: this.data.canvasText + "\n佩戴状态：" + JSON.stringify(res)
        })
      }
    })
    appControlAPI.bloodPressureMeasureController(continuous, (status, res) => {
      console.log("状态", status);
      console.log("结果", res);
    })
  },
  // 关闭血压测试
  bloodPressureMeasureStop() {
    appControlAPI.bloodPressureMeasureController(0x00, (status, res) => {
      console.log("状态", status);
      console.log("结果", res);
    })
  },
  // 开启ECG上传
  uploadECGDataStart() {
    alertUtil.handleToast("命令执行中", "loading", 0)
    appControlAPI.receiveRealTimeData((realTimeDataType, res) => {
      if (realTimeDataType == receivedRealTimeECG) {
        util.printLog(JSON.stringify(res))
        this.setData({
          canvasText: this.data.canvasText + "\n实时ECG：" + JSON.stringify(res)
        })
        alertUtil.closeToast()
      }
    })

    appControlAPI.waveDataUploadControl(waveUploadStateUploadWithOutSerialnumber, waveUploadDataTypeECG, (state, res) => {
      if (state == 0) {
        this.setData({
          canvasText: this.data.canvasText + "\n开启ECG上传：success"
        })
      } else {
        this.setData({
          canvasText: this.data.canvasText + "\n开启ECG上传：fail"
        })
      }
      alertUtil.closeToast()
    })
  },
  // 关闭ECG上传
  uploadECGDataStop() {
    alertUtil.handleToast("命令执行中", "loading", 0)
    appControlAPI.waveDataUploadControl(waveUploadStateOff, waveUploadDataTypeECG, (state, res) => {

      if (state == 0) {
        this.setData({
          canvasText: this.data.canvasText + "\n关闭ECG上传：success"
        })
      } else {
        this.setData({
          canvasText: this.data.canvasText + "\n关闭ECG上传：fail"
        })
      }
      alertUtil.closeToast()
    })
  },
  // 开始测量ECG
  startECG() {

    // 开启血压监测
    appControlAPI.bloodPressureMeasureController(continuous, (status, res) => {
      if (status == succeed) {
        this.setData({
          canvasText: this.data.canvasText + "\n开启血压监测：success"
        })
        // 开启实时ECG上传
        appControlAPI.waveDataUploadControl(waveUploadStateUploadWithOutSerialnumber, waveUploadDataTypeECG, (state, res) => {
          if (state == 0) {
            this.setData({
              canvasText: this.data.canvasText + "\n开启ECG上传：success"
            })
            // 开启实时获取血压数据
            appControlAPI.realTimeDataUplod(true, realBloodPressureUpload, (state, res) => {
              if (state == succeed) {
                this.setData({
                  canvasText: this.data.canvasText + "\n开启实时获取血压：success"
                })
              } else {
                this.setData({
                  canvasText: this.data.canvasText + "\n开启实时获取血压：fail"
                })
              }
            })
            // 开启实时获取hrv数据
            appControlAPI.realTimeDataUplod(true, realHrvUpload, (state, res) => {
              if (state == succeed) {
                this.setData({
                  canvasText: this.data.canvasText + "\n开启实时获取hrv：success"
                })
              } else {
                this.setData({
                  canvasText: this.data.canvasText + "\n开启实时获取hrv：fail"
                })
              }
            })
            // 监听血压、ECG数据、PPG数据
            appControlAPI.receiveRealTimeData((realTimeDataType, res) => {
              if (realTimeDataType == receivedRealTimeECG) {
                util.printLog(JSON.stringify(res))
                // this.setData({
                //   canvasText: this.data.canvasText + "\n实时ECG：" + JSON.stringify(res)
                // })
              } else if (realTimeDataType == receivedRealTimeBloodPressure) {
                // util.printLog(JSON.stringify(res))
                this.setData({
                  canvasText: this.data.canvasText + "\n实时血压：" + JSON.stringify(res)
                })
              } else if (realTimeDataType == receivedRealTimePPG) {
                // util.printLog(JSON.stringify(res))
                this.setData({
                  canvasText: this.data.canvasText + "\n实时PPG：" + JSON.stringify(res)
                })
              } else if (realTimeDataType == measureECGStatus) {
                this.setData({
                  canvasText: this.data.canvasText + "\n测量ECG结束：" + JSON.stringify(res)
                })
              }
            })
            // 开启PPG上传
            appControlAPI.waveDataUploadControl(waveUploadStateUploadWithOutSerialnumber, waveUploadDataTypePPG, (state, res) => {
              if (state == succeed) {
                this.setData({
                  canvasText: this.data.canvasText + "\n开启PPG上传：success"
                })
              } else {
                this.setData({
                  canvasText: this.data.canvasText + "\n开启PPG上传：fail"
                })
              }
              alertUtil.closeToast()
            })
          } else {
            this.setData({
              canvasText: this.data.canvasText + "\n开启ECG上传：fail"
            })
          }
          alertUtil.closeToast()
        })
      }
    })

  },

})